package com;

import com.handler.inbound.FileUploadJudgment;
import com.handler.inbound.WriterQueue;
import com.handler.inbound.MetaInfoDecoder;
import com.handler.outbound.MetaInfoEncoder;
import com.handler.utils.FileWriter;
import com.to.FileReq;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LoggingHandler;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Server {


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        EventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup(2);

        LinkedBlockingQueue<FileReq> fileReqs = new LinkedBlockingQueue<>();

        ChannelFuture channelFuture = new ServerBootstrap()
                .group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {

                        ch.pipeline().addLast(
//                                入栈
//                                new LoggingHandler(),
                                new LengthFieldPrepender(2, 0, false),
                                new MetaInfoEncoder(),

//                                出栈
                                new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2),
                                new MetaInfoDecoder(),
                                new FileUploadJudgment(),
                                new WriterQueue(fileReqs)

                        );

                    }
                }).bind("127.0.0.1", 38888);

        channelFuture.get();

        if (channelFuture.isSuccess()) {
            System.out.println("服务器启动成功！！");
        }

        new Thread(new FileWriter(fileReqs)).start();


        TimeUnit.HOURS.sleep(1);
    }
}

